前幾天寫了一個錯誤的寫法,
大致上的關係長的像是下面這樣
出錯的地方在於我在 .h
檔裏面定義了一個變數
為何不可以這樣寫、以及要如何在 .h
檔裏面定義變數
的細節其實也還不是很清楚,
但總之就先把錯誤的寫法紀錄下來
// hello.h
#ifndef HELLO_H
#define HELLO_H
char *str = "Hello World\n";
void say_hello();
#endif
// hello.c
#include <stdio.h>
#include "hello.h"
void say_hello()
{
printf("%s", str);
}
// main.c
#include "hello.h"
int main(int argc, char **argv)
{
say_hello();
return 0;
}
編譯:
$ gcc -c main.c
$ gcc -c hello.c
$ gcc -o hello_world main.o hello.o
/usr/bin/ld: hello.o:(.data.rel.local+0x0): multiple definition of `str'; main.o:(.data.rel.local+0x0): first defined here
collect2: error: ld returned 1 exit status